package com.wlts.wzy.DYUserModule.controller;


import com.alibaba.fastjson.JSON;

import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.DYUserModule.entity.DyOauth;
import com.wlts.wzy.DYUserModule.entity.DyStoreUser;
import com.wlts.wzy.DYUserModule.service.IDyOauthService;
import com.wlts.wzy.DYUserModule.service.IDyStoreUserService;
import com.wlts.wzy.DYUserModule.util.UserUtil;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.dy.GetMyDyOauthRequest;
import com.wlts.wzy.api.request.dy.UpdateDyUserInfoRequest;
import com.wlts.wzy.api.response.dy.DyOauthResponse;
import com.wlts.wzy.configBean.DyConfig.DyConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * <p>
 * 抖音授权信息 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-02-20
 */
@Api(tags = "抖音授权信息 前端控制器")
@RestController
@RequestMapping("/DYUserModule/dy-oauth")
public class DyOauthController {

    @Autowired
    private IDyOauthService dyOauthService;
    @Autowired
    private IDyStoreUserService dyStoreUserService;
    @Autowired
    private DyConfig dyConfig;

    @ApiOperation(value = "获取我的授权")
    @RequestMapping(value = "/getMyOauth", method = RequestMethod.POST)
    public Result<DyOauth> getMyOauth(@RequestBody GetMyDyOauthRequest request) {

        MyLambdaQueryWrapper<DyOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(DyOauth::getUserUuid, request.getUserUuid());

        DyOauth dyOauth = dyOauthService.getOne(queryWrapper);

        return Result.buildResult(dyOauth);

    }


    @ApiOperation(value = "更新商铺信息")
    @RequestMapping(value = "updateStoreInfo", method = RequestMethod.POST)
    public Result<DyStoreUser> updateStoreInfo(@RequestBody UpdateDyUserInfoRequest request) {

        MyLambdaQueryWrapper<DyStoreUser> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(DyStoreUser::getUuid, request.getUserUuid());

        wrapper.eq(BaseEntity::getDelFlag, "0");

        //      wrapper.eq(DyStoreUser::getPassword, MD5.md5(request.getPassword()));

        DyStoreUser dyStoreUser = dyStoreUserService.getOne(wrapper);

        if (dyStoreUser == null) {
            return Result.buildResult(500, "用户不存在");
        }

        if(StringUtils.isEmpty(dyStoreUser.getAppKey())&&StringUtils.isEmpty(request.getAppKey())){
            return Result.buildResult(500, "请填写appKey和appSecret");
        }

        MyLambdaQueryWrapper<DyOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(DyOauth::getUserUuid, dyStoreUser.getUuid());

        DyOauth dyOauth = dyOauthService.getOne(queryWrapper);

        if (dyOauth == null) {
            dyOauth=new DyOauth();
        }

        DyOauthResponse response = UserUtil.getAccessToken(dyStoreUser.getAppKey(),dyStoreUser.getAppSecret());

        if(response==null){
            return Result.buildResult(500,"授权失败");
        }

        dyOauth.setUserUuid(request.getUserUuid());
        dyOauth.setAccessToken(response.getAccessToken());
        dyOauth.setRefreshToken(response.getRefreshToken());
        dyOauth.setExpiresIn(response.getExpiresIn());
      //  dyOauth.setOpenId(response.getOpenId());
        //access_token过期时间，单位秒，默认为172800，即48小时
        dyOauth.setTokenOverTime(LocalDateTime.now().plusSeconds(response.getExpiresIn()));
        dyOauth.setMessageStatus(0);
        dyOauth.setTokenStatus(0);

        dyOauthService.saveOrUpdate(dyOauth);

        return Result.buildResult(dyStoreUser);
    }



    @ApiOperation(value = "刷新授权")
    @RequestMapping(value = "updateAuth", method = RequestMethod.POST)
    public Result<DyStoreUser> updateAuth() {

        DyStoreUser storeUser = dyConfig.getDyStoreUserConfig();

        if (storeUser == null) {
            return Result.buildResult(500, "用户不存在");
        }


        MyLambdaQueryWrapper<DyOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(DyOauth::getUserUuid, storeUser.getUuid());

        DyOauth dyOauth = dyOauthService.getOne(queryWrapper);

        if (dyOauth == null) {
            dyOauth=new DyOauth();
        }

        DyOauthResponse response = UserUtil.getAccessToken(storeUser.getAppKey(),storeUser.getAppSecret());

        if(response==null){
            return Result.buildResult(500,"授权失败");
        }

        dyOauth.setUserUuid(storeUser.getUuid());
        dyOauth.setAccessToken(response.getAccessToken());
        dyOauth.setRefreshToken(response.getRefreshToken());
        dyOauth.setExpiresIn(response.getExpiresIn());
        //  dyOauth.setOpenId(response.getOpenId());
        //access_token过期时间，单位秒，默认为172800，即48小时
        dyOauth.setTokenOverTime(LocalDateTime.now().plusSeconds(response.getExpiresIn()));
        dyOauth.setMessageStatus(0);
        dyOauth.setTokenStatus(0);
        dyOauth.setShopId(response.getShopId());

        MyLambdaQueryWrapper<DyStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

        userWrapper.eq(DyStoreUser::getUuid, dyOauth.getUserUuid());

        userWrapper.eq(BaseEntity::getDelFlag, "0");

        //      wrapper.eq(DyStoreUser::getPassword, MD5.md5(request.getPassword()));

        DyStoreUser user = dyStoreUserService.getOne(userWrapper);

        user.setDySellerId(response.getShopId());

        user.setDyName(response.getShopName());

        dyStoreUserService.updateById(user);

        dyOauthService.saveOrUpdate(dyOauth);

        return Result.buildResult(storeUser);
    }
}
